//
//  ChartYAxisView.m
//  ChartDemoX
//
//  Created by yuanpt on 17/5/6.
//  Copyright © 2017年 yuanpt. All rights reserved.
//

#import "ChartYAxisView.h"
#import "ChartView.h"
#import "ChartUtils.h"
#import "UIColor+Extensions.h"

@implementation ChartYAxisView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) return nil;
    self.backgroundColor = [UIColor whiteColor];
#ifdef DEBUG
    self.backgroundColor = [UIColor whiteColor];
#endif
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    CGFloat yMaxValue = self.chartView.yMaxValue;
    CGFloat yGridValue = self.chartView.yGridValue;
    CGFloat yMinValue = self.chartView.yMinValue;
    
    CGFloat height = rect.size.height;
    
    NSString *maxString = @((NSInteger)yMaxValue).stringValue;
    NSString *minString = @((NSInteger)yMinValue).stringValue;
    NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSTextAlignmentCenter];

    NSDictionary *attr = @{
                           NSFontAttributeName: [UIFont systemFontOfSize:11.0f],
                           NSParagraphStyleAttributeName: style
                           
                           };
    CGFloat pointX = 35;
    NSTextAlignment align = NSTextAlignmentRight;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [ChartUtils drawText:context text:maxString point:CGPointMake(pointX, 0) align:NSTextAlignmentRight attributes:attr];
    CGSize minStringSize = [minString sizeWithAttributes:attr];
    [ChartUtils drawText:context text:minString point:CGPointMake(pointX, height - minStringSize.height) align:align attributes:attr];
    
    CGFloat commonStringHeight = minStringSize.height;
    
    CGFloat deltaValue = yMaxValue - yMinValue;
    // 有多少大格子
    CGFloat countOfSplit = deltaValue / yGridValue;
    
    // 每个大格子的高度
    CGFloat bigSplitHeigth = height / countOfSplit;
    
    // 每个小格子的高度
//    CGFloat smallSplitHeigth = bigSplitHeigth / yGridSplit;
    
    for (NSInteger i = 1; i < (NSInteger)countOfSplit; i++) {
        NSString *numberString = @((NSInteger)(yMaxValue - i * yGridValue)).stringValue;
        [ChartUtils drawText:context text:numberString point:CGPointMake(pointX, i * bigSplitHeigth - commonStringHeight * 0.5) align:align attributes:attr];
    }
}

@end

